package com.lnking.lnkingplace.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lnking.lnkingplace.Util.UserUtil;
import com.lnking.lnkingplace.mapper.RectificationMapper;
import com.lnking.lnkingplace.model.dto.activity.ActivityDetailDto;
import com.lnking.lnkingplace.model.dto.rectification.RectificationDetailDto;
import com.lnking.lnkingplace.model.dto.rectification.RectificationResultDto;
import com.lnking.lnkingplace.model.dto.user.UserDto;
import com.lnking.lnkingplace.model.entity.Inspect;
import com.lnking.lnkingplace.model.entity.InspectResult;
import com.lnking.lnkingplace.model.entity.RecordUser;
import com.lnking.lnkingplace.model.entity.Rectification;
import com.lnking.lnkingplace.model.enums.RectificationStatus;
import com.lnking.lnkingplace.model.enums.RectificationType;
import com.lnking.lnkingplace.model.request.inspect.InspectResultRequest;
import com.lnking.lnkingplace.model.request.rectification.*;
import com.lnking.lnkingplace.service.IInspectResultService;
import com.lnking.lnkingplace.service.IRectificationService;
import com.lnking.starter.mybatis.service.impl.CustomServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sn
 * @since 2022-08-19
 */
@Service
public class RectificationServiceImpl extends CustomServiceImpl<RectificationMapper, Rectification> implements IRectificationService {

    @Autowired
    UserUtil userUtil;

    public static final String TRUE="是";
    public static final String OK="达标";
    public static final String NO="否";
    public static final String FAIL="不达标";
    public static final String REVIEW="复查";
    public static final String RECTIFIED ="已整改";
    public static final String LOCATION="场所负责人";
    public static final String RESULT ="场所负责人已确认";
    public static final String ELSERESULT ="从业人员代确认";
    public static final String SUPERRESULT ="监管人员代确认";

    @Autowired
    IInspectResultService iInspectResultService;
    @Override
    public void add(RectificationAddRequest params) throws Exception {
        Rectification entity = new Rectification();
        BeanUtils.copyProperties(params, entity);
        // 自查
        entity.setStatus(RectificationStatus.BEFORE);
        entity.setInspectResult(RectificationStatus.FAIL);
        entity.setType(RectificationType.SELF);
        getBaseMapper().insert(entity);
    }

    @Override
    public void update(RectificationUpdateRequest params) {
        Rectification entity = new Rectification();
        BeanUtils.copyProperties(params, entity);
        getBaseMapper().updateById(entity);
    }

    /**
     * 场所确认 修改状态
     * @param id
     */
    @Override
    public void placeTrue(String id) {
        Rectification byId = getById(id);
        byId.setStatus(RectificationStatus.START);
        getBaseMapper().updateById(byId);
    }

    @Override
    public RectificationDetailDto getDetailById(String id) {
        return getBaseMapper().getDetailById(id);
    }

    /**
     * 复查修改 状态，结果，复查时间
     * @param params
     */
    @Override
    public void review(InspectResult  params) throws Exception {
        Assert.notNull(params.getPlaceContent(),"场所未整改完成");
        params.setTime(LocalDateTime.now());
    iInspectResultService.getBaseMapper().updateById(params);
    }



    /**
     * 场所确认整改
     * 生成复查表
     */
    @Override
    public void finish(InspectResultTrueRequest params) {
        InspectResult inspectResult = iInspectResultService.getById(params.getId());
        inspectResult.setPlaceTime(LocalDateTime.now());
        inspectResult.setPlaceContent(RECTIFIED);
        inspectResult.setPlacePhotos(params.getPlacePhotos());
        inspectResult.setPlaceText(params.getPlaceText());
        iInspectResultService.getBaseMapper().updateById(inspectResult);
    }

    @Override
    public List<Inspect> getFail(String id) {
        return getBaseMapper().getFail(id);
    }

    @Override
    public List<RectificationResultDto> getResult(String inspectId, String placeId) {
        List<RectificationResultDto> rectificationResultDtoList = new ArrayList<>();

        // Rectification
        QueryWrapper<Rectification> wapper=new QueryWrapper<>();
        wapper.lambda().eq(Rectification::getPlaceId,placeId);
        wapper.lambda().eq(Rectification::getInspectId,inspectId);
        wapper.lambda().eq(Rectification::getDelFlag,false);
        wapper.lambda().orderByAsc(Rectification::getSort);
        List<Rectification> rectificationList = getBaseMapper().selectList(wapper);
        for (Rectification rectification : rectificationList) {
            RectificationResultDto rectificationResultDto =new RectificationResultDto();
            BeanUtils.copyProperties(rectification,rectificationResultDto);
            List<InspectResult> byRectificationId = iInspectResultService.getByRectificationId(rectification.getId());
            rectificationResultDto.setList(byRectificationId);
            rectificationResultDtoList.add(rectificationResultDto);
        }
        return rectificationResultDtoList;
    }

    @Override
    public Rectification getReview(String placeId, String inspectId) {
        return getBaseMapper().getReview(placeId,inspectId);
    }

    @Override
    public Rectification getLastRecord(String placeId, String inspectId) {
        return  getBaseMapper().getLastRecord(placeId,inspectId);
    }

    @Override
    public Rectification getRectification(String placeId, String inspectId, Integer sort) {
        return getBaseMapper().getRectification(placeId,inspectId,sort);
    }

    @Override
    public void reviewResult(String rectificationId) throws Exception {
        Rectification rectification = getById(rectificationId);
        List<InspectResult> inspectResultList = iInspectResultService.getByRectificationId(rectificationId);
        // 验证是否传入值
        for (InspectResult inspectResult : inspectResultList) {
            if (null == inspectResult.getStatus()) {
                throw new Exception("未复查完毕");
            }
        }
        long ok = inspectResultList.stream().filter(e -> !e.getStatus().equals(TRUE)).count();
        if (ok == 0 && rectification.getInspectResult() == null) {
            // 达标
            rectification.setInspectResult(OK);
        }
        if (ok != 0 && rectification.getInspectResult() == null) {
            // 不达标
            rectification.setInspectResult(FAIL);

            // 生成复查表
            Rectification review = new Rectification();
            review.setPlaceId(rectification.getPlaceId());
            review.setInspectId(rectification.getInspectId());
            review.setSort(rectification.getSort() + 1);
            review.setType(REVIEW);
            getBaseMapper().insert(review);
            List<InspectResult> inspectResults =new ArrayList<>();
            // 替换整改id
            for (InspectResult inspectResult : inspectResultList.stream().filter(e -> NO.equals(e.getStatus())).collect(Collectors.toList())) {
                inspectResult.setId(null);
                inspectResult.setStatus(null);
                inspectResult.setPlaceContent(null);
                inspectResult.setPlaceTime(null);
                inspectResult.setTime(LocalDateTime.now());
                inspectResult.setRectificationId(review.getId());
                inspectResult.setCreateTime(LocalDateTime.now());
                inspectResults.add(inspectResult);
            }
            // 批量添加
            iInspectResultService.saveBatch(inspectResults);

        }
        UserDto user = userUtil.getUser();
        rectification.setInspectTime(LocalDateTime.now());
        rectification.setInspectPersonId(user.getId());
        rectification.setInspectPersonName(user.getName());
        updateById(rectification);
    }

    @Override
    public Rectification getAfterInspect(String inspectId, String placeId) {
        QueryWrapper<Rectification> Swapper =new QueryWrapper<>();
        Swapper.lambda().eq(Rectification::getInspectId,inspectId);
        Swapper.lambda().eq(Rectification::getPlaceId,placeId);
        Swapper.lambda().eq(Rectification::getSort,1);
        return  getBaseMapper().selectOne(Swapper);
    }

    @Override
    public Rectification getCheck(String inspectId,String placeId) {
        QueryWrapper<Rectification> Swapper =new QueryWrapper<>();
        Swapper.lambda().eq(Rectification::getInspectId,inspectId);
        Swapper.lambda().eq(Rectification::getPlaceId,placeId);
        Swapper.lambda().eq(Rectification::getSort,0);
        Swapper.lambda().eq(Rectification::getDelFlag,0);
        return  getBaseMapper().selectOne(Swapper);
    }

    @Override
    public void resultStatus(String inspectId  ,String placeId) {
        //检查情况
        Rectification check = getCheck(inspectId, placeId);
        // 获取登录人的名字
        UserDto user = userUtil.getUser();
        check.setConfirmTime(LocalDateTime.now());
        check.setConfirmUser(user.getName());
        if(StringUtils.isNotBlank(user.getPlaceId())){
            // 场所确认
            if(user.getType().equals(LOCATION)){
                check.setStatus(RESULT);
            }else{
                check.setStatus(ELSERESULT);
            }

        }else{
            // 监管代确认
            check.setStatus(SUPERRESULT);
        }
        getBaseMapper().updateById(check);
    }

}
